﻿var app = angular.module("App", []);
var firebase = 'https://ccamplessons.firebaseio.com/';

app.controller("HomeController", function ($scope, ContactFactory) {

    $scope.contacts = ContactFactory.contactArray;

    $scope.addContact = function () {
        var contactObj = new ContactFactory.Contact($scope.name, $scope.email, $scope.phoneNumber);
        ContactFactory.postContact(contactObj).then(function (data) {
            console.log('in controller');
            console.log(data);
            $scope.contacts.push(data);
        });

        console.log("Running after AJAX call");
    };
});

app.factory("ContactFactory", function ($http, $q) {
    var Contact = function (name, email, phoneNumber) {  //  Angular: Would be $scope.Contact = function .... (LIKE REGULAR CONSTRUTOR)
        this.name = name;
        this.email = email;
        this.phoneNumber = phoneNumber;
    };

    var contactArray = [new Contact("Russell", "info@gmail.com", "555-555-5555"),
        new Contact("Another Guy", "His Email", "Fake Number"),
        new Contact("That one", "over there", "don'tcha know?")];


    var getContacts = function () {

    };
    //
    var postContact = function (Contact) {
        var def = $q.defer();

        $http({
            url: firebase + '.json',
            method: 'POST',
            data: Contact
        }).success(function (data) {
            Contact.key = data.name;
            console.log('in factory');
            console.log(Contact);
            //send back Contact to the controller
            def.resolve(Contact);
        }).error(function (data) {
            console.log(data);
            def.reject();
        });

        return def.promise;
    };

    // Must return; Variables act like private variables inside function 
    return {
        Contact: Contact,
        contactArray: contactArray,
        getContacts: getContacts,
        postContact: postContact
    }
});